﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using FirstWebSite.AuthenticationServiceClient;

namespace FirstWebSite
{
    public partial class MasterFirstWebSite : System.Web.UI.MasterPage
    {
        private AuthenticationServiceClient.AuthenticationServiceClient client = null;

        public MasterFirstWebSite()
        {
            client = new FirstWebSite.AuthenticationServiceClient.AuthenticationServiceClient();
        }

        /// <summary>
        /// Handles the Load event of the Page control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void Page_Load(object sender, EventArgs e)
        {
            User User = Session["User"] as User;
            if (User == null)
            {
                string token = Request.QueryString["token"];

                if (string.IsNullOrEmpty(token))
                {
                    Response.Redirect("Login.aspx");
                    return;
                }
                ValidateToken(token);
            }

        }

        /// <summary>
        /// Validates the token.
        /// </summary>
        /// <param name="token">The token.</param>
        private void ValidateToken(string token)
        {
            TokenRequest tokenRequest = new TokenRequest();
            tokenRequest.Token = new Token
            {
                Id = token
            };
            TokenResponse tokenResponse = client.ValidateToken(tokenRequest);

            if (null == tokenResponse.Fault && null != tokenResponse.User)
            {
                Session["User"] = tokenResponse.User;
                Response.Redirect(Request.Path);
                return;
            }
            Response.Redirect("Login.aspx");
        }

    }
}
